package cn.uin.infrastructure.adapter.repository;

import cn.uin.domain.auth.model.entity.HomeUserEntity;
import cn.uin.domain.auth.service.user.SecurityContextService;
import cn.uin.domain.family.adapter.repository.IFamilyRepository;
import cn.uin.domain.family.model.entity.HomeFamilyEntity;
import cn.uin.domain.family.model.entity.HomeFamilyListEntity;
import cn.uin.domain.family.model.valobj.FamilyAddStatusTypeEnum;
import cn.uin.domain.family.model.valobj.FamilyRoleTypeEnum;
import cn.uin.infrastructure.dao.HomeFamilyDao;
import cn.uin.infrastructure.dao.HomeFamilyListDao;
import cn.uin.infrastructure.dao.HomeUserDao;
import cn.uin.infrastructure.dao.po.HomeFamily;
import cn.uin.infrastructure.dao.po.HomeFamilyList;
import cn.uin.infrastructure.dao.po.HomeUser;
import cn.uin.infrastructure.redis.IRedisService;
import cn.uin.types.common.RedisConstants;
import com.sun.xml.internal.bind.v2.TODO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName FamilyRepository
 * @Description:类描述
 * @Author: Administrator
 * @CreateDate: 2025/11/11 16:23
 * @Version: 1.0
 */
@Slf4j
@Repository
public class FamilyRepository implements IFamilyRepository {

	@Resource
	private HomeFamilyDao homeFamilyDao;

	@Resource
	private HomeFamilyListDao homeFamilyListDao;

	@Resource
	private SecurityContextService securityContextService;

	@Resource
	private HomeUserDao homeUserDao;

	@Resource
	private IRedisService redisService;

	@Override
	public HomeFamilyEntity queryFamilyById(Long familyId) {
		HomeFamily homeFamily = homeFamilyDao.queryById(familyId);
		if (ObjectUtils.isEmpty(homeFamily)) return null;
		HomeFamilyEntity homeFamilyEntity = HomeFamilyEntity.builder().build();
		BeanUtils.copyProperties(homeFamily, homeFamilyEntity);
		return homeFamilyEntity;
	}

	@Override
	public HomeFamilyListEntity queryFamilyListByUserId(Long userId) {
		HomeFamilyList homeFamilyList = homeFamilyListDao.queryByUserId(userId);
		if (ObjectUtils.isEmpty(homeFamilyList)) return null;

		HomeFamilyListEntity homeFamilyListEntity = HomeFamilyListEntity.builder().build();
		BeanUtils.copyProperties(homeFamilyList, homeFamilyListEntity);
		return homeFamilyListEntity;
	}

	@Override
	public List<HomeFamilyListEntity> queryOtherFamilyList(Long userId) {
		List<HomeFamilyList> homeFamilyLists = homeFamilyListDao.queryOtherFamilyList(userId);
		if (CollectionUtils.isEmpty(homeFamilyLists)) return null;

		return homeFamilyLists.stream().map(item -> {
			HomeFamilyListEntity homeFamilyListEntity = HomeFamilyListEntity.builder().build();
			BeanUtils.copyProperties(item, homeFamilyListEntity);
			return homeFamilyListEntity;
		}).collect(Collectors.toList());
	}

	@Override
	public String checkTokenAndActivateAddFamily(String token, String email, Long familyId, RedirectAttributes redirectAttributes, Model model) {
		String dbToken = redisService.getValue(RedisConstants.ADD_FAMILY_TOKEN + email);
		if (StringUtils.isEmpty(dbToken)) {
			// 动态传递错误信息
			model.addAttribute("errorMsg", "链接已过期或无效");
			return "email-error";
		}
		if (!dbToken.equals(token)) {
			model.addAttribute("errorMsg", "链接token有误");
			return "email-error";
		}
		HomeUser homeUser = homeUserDao.queryUserByEmail(email);
		if (ObjectUtils.isEmpty(homeUser)) {
			model.addAttribute("errorMsg", "用户:{"+homeUser.getUsername()+"}未绑定邮箱,请绑定后重试");
			return "email-error";
		}

		// TODO 后续调整为异步MQ处理
		// 调整成员状态为已加入,并累加家庭人员总数
		homeFamilyListDao.updateAddStatusByUserId(homeUser.getId(), FamilyAddStatusTypeEnum.ACCEPT.getCode());
		homeFamilyDao.updateFamilyNum(familyId);

		// 动态传递成功信息
		model.addAttribute("username", homeUser.getUsername());
		return "email-success";
	}

	@Override
	public void insert(HomeFamilyEntity homeFamilyEntity) {
		HomeFamily homeFamily = HomeFamily.builder().build();
		BeanUtils.copyProperties(homeFamilyEntity, homeFamily);

		HomeFamily dbHomeFamily = homeFamilyDao.insert(homeFamily);

		// 获取当前用户
		HomeUserEntity currentUser = securityContextService.getCurrentUser();

		// 保存成员信息(创建人直接为"管理员",状态直接为"已接受")
		HomeFamilyList homeFamilyList = HomeFamilyList.builder()
				.userId(currentUser.getId())
				.familyId(dbHomeFamily.getId())
				.role(FamilyRoleTypeEnum.ADMIN.getInfo())
				.addStatus(FamilyAddStatusTypeEnum.ACCEPT.getCode())
				.build();
		homeFamilyListDao.insert(homeFamilyList);
	}
}
